<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html {
            width: 100%;
            height: 100%;
        }

        body {
            width: 100%;
            height: 2400px;
        }

        div {
            text-align: center;
            width: 45px;
            height: 45px;
            background-color: pink;
            position: fixed;
            right: 30px;
            bottom: 30px;
            cursor: pointer;
            display: none;
        }
    </style>
</head>

<body>

    <div class="gotop">返回顶部</div>
</body>

</html>
<script src='https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js'></script>
<script>
    //滚动条滚动到某个位置的时候 让这个gotop显示

    $(window).scroll(function () {
        //获取scrollTop 大于300px的时候 让gotop显示出来
        if ($(window).scrollTop() >= 300) {
            $(".gotop").fadeIn(500)
        } else {
            $(".gotop").fadeOut(500)
        }
    })

    //点击gotop要让滚动条返回到顶部 并且要有丝滑的过渡

    $(".gotop").click(function () {
        //设置scrollTop
        // $(window).scrollTop(0)
        $("html,body").animate({
            scrollTop: 0
        },2000)
    })
</script>